import { defineStore } from 'pinia';
import { login, getCurrentUser, logout, checkAuthStatus } from '@/api/auth';

interface User {
  id: number | string;
  username: string;
  role: string;
  email?: string;
  realName?: string;
  department?: string;
  [key: string]: any;
}

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
  rememberMe: boolean;
}

/**
 * 认证状态管理
 */
export const useAuthStore = defineStore('auth', {
  // 状态
  state: (): AuthState => ({
    user: null,
    isAuthenticated: false,
    loading: false,
    error: null,
    rememberMe: false
  }),
  
  // 计算属性
  getters: {
    currentUser: state => state.user,
    isLoggedIn: state => state.isAuthenticated,
    userRole: state => state.user?.role || null,
  },
  
  // 方法
  actions: {
    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @param rememberMe 记住我
     */
    async login(username: string, password: string, rememberMe = false) {
      this.loading = true;
      this.error = null;
      this.rememberMe = rememberMe;
      
      try {
        const response = await login(username, password);
        // 从response.data中提取用户信息
        const userData = response.data;
        this.user = userData;
        this.isAuthenticated = true;
        
        return userData;
      } catch (error: any) {
        this.error = error?.response?.data?.message || '登录失败，请检查用户名和密码';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 检查登录状态
     */
    async checkAuth() {
      if (this.isAuthenticated && this.user) {
        return this.user;
      }
      
      try {
        const userData = await getCurrentUser();
        this.user = userData;
        this.isAuthenticated = true;
        return userData;
      } catch (error) {
        this.user = null;
        this.isAuthenticated = false;
        throw error;
      }
    },
    
    /**
     * 自动登录
     */
    async autoLogin() {
      try {
        const userData = await checkAuthStatus();
        if (userData) {
          this.user = userData;
          this.isAuthenticated = true;
          return userData;
        }
        return null;
      } catch (error) {
        return null;
      }
    },
    
    /**
     * 退出登录
     */
    async logout() {
      try {
        await logout();
      } finally {
        this.user = null;
        this.isAuthenticated = false;
      }
    },
    
    /**
     * 更新用户信息
     * @param userData 用户数据
     */
    updateUserInfo(userData: Partial<User>): void {
      if (this.user) {
        this.user = { ...this.user, ...userData };
      }
    }
  }
}); 